package com.example.oauth;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.Regexp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
public class MyLoginController {

    private Logger logger = LoggerFactory.getLogger(MyLoginController.class);
    private RequestCache requestCache = new HttpSessionRequestCache();

    @Autowired
    ClientDetailsService clientDetailsService;

    @GetMapping("/mylogin")
    @ResponseBody
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public void myLogin(HttpServletRequest request,
                                          HttpServletResponse response) throws IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        logger.debug("saved request: {}", savedRequest);


        if (savedRequest == null) {
            response.getWriter().write("need visit authorize url");
            return;
        }

        String redirectuUrl = savedRequest.getRedirectUrl();
        Pattern p = Pattern.compile("client_id\\=([a-zA-Z0-9_]+)\\&?");
        Matcher matcher = p.matcher(redirectuUrl);
        String clientId = "";
        if (matcher.find()) {
            clientId = matcher.group(1);
        }

        if (StringUtils.isEmpty(clientId)) {
//            ret = new ResponseEntity<>("client_id not found in url.", HttpStatus.BAD_REQUEST);
//            return ret;
            response.getWriter().write("client_id not found in url");
            return;
        }


        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
        if (clientDetails == null) {
//            ret = new ResponseEntity<>("client id not found.", HttpStatus.UNAUTHORIZED);
//            return ret;
            response.getWriter().write("client id not found.");
            return;
        }

        Map<String, Object> infos = clientDetails.getAdditionalInformation();
        if(infos.containsKey("loginPage")){
            response.sendRedirect(infos.get("loginPage").toString());
            return;
        }

        if(infos.containsKey("mainPage")){
            response.sendRedirect(infos.get("mainPage").toString());
            return;
        }

//        clientDetailsService.
    }
}
